package router

import (
	"bigStudy/util"
	"fmt"
	"log"
	"net/http"
	"path"

	"github.com/gin-gonic/gin"
)

//homePage: 首页
func homePage(c *gin.Context) {
	c.HTML(http.StatusOK, "home.html", nil)
}

// 班级主页
func classPage(c *gin.Context) {
	class := c.Param("class")
	isClass := util.ClassPageExists(class)
	if isClass {
		c.HTML(http.StatusOK, "classindex.html", gin.H{
			"class": class,
		})
	} else {
		c.HTML(http.StatusOK, "hint.html", gin.H{
			"msg": "班级不存在!请创建班级",
		})
	}

}

//NoResponse 请求的url不存在，返回404
func NoResponse(c *gin.Context) {
	//返回404状态码
	c.HTML(http.StatusOK, "404.html", nil)
}

// submitEndpoint 提交
func submitEndpoint(c *gin.Context) {
	class := c.Param("class")
	isClass := util.ClassPageExists(class)
	if isClass {
		c.HTML(http.StatusOK, "submit.html", gin.H{
			"class": class,
		})
	} else {
		c.HTML(http.StatusOK, "hint.html", gin.H{
			"msg": "班级不存在!请创建班级",
		})
	}

}

// uploadEndpoint 上传
func uploadEndpoint(c *gin.Context) {
	// 从请求中读取文件,并将读取到的文件保存到(服务器)本地
	username := c.PostForm("name")
	class := c.Param("class")

	form, err := c.MultipartForm()
	files := form.File["file"]
	log.Println(form)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
	} else {
		for index, file := range files {
			log.Println(file.Filename)
			// filePath := path.Join("./", fh.Filename)
			fileSuffix := path.Ext(file.Filename)
			filePath := fmt.Sprintf("./img/%s/%s-%s(%d)%s", class, class, username, index+1, fileSuffix)
			c.SaveUploadedFile(file, filePath)
			// 缩略图
			sfilePath := fmt.Sprintf("./cache/%s/%s-%s(%d)%s", class, class, username, index+1, fileSuffix)
			util.CompressImg(filePath, sfilePath)
		}

		c.HTML(http.StatusOK, "hint.html", gin.H{
			"msg": "提交成功!",
		})
	}
}

func readEndpoint(c *gin.Context) {
	class := c.Param("class")
	isClass := util.ClassPageExists(class)
	if isClass {
		filePath := fmt.Sprintf("./img/%s", class)
		list := util.ListFile(filePath)
		data := make(map[int]string)
		for index, val := range list {
			data[index+1] = val
		}
		datalen := len(data)
		c.HTML(http.StatusOK, "read.html", gin.H{
			"class":   class,
			"data":    data,
			"datalen": datalen,
		})
	} else {
		c.HTML(http.StatusOK, "hint.html", gin.H{
			"msg": "班级不存在!请创建班级",
		})
	}
}

func downEndpoint(c *gin.Context) {
	class := c.Query("class")
	isClass := util.ClassPageExists(class)

	if isClass {
		// 压缩
		sourcePath := fmt.Sprintf("./img/%s", class)
		goalPath := fmt.Sprintf("./export/%s/z.zip", class)
		util.Zip(sourcePath, goalPath)

		// fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名
		filename := fmt.Sprintf("软件%s团支部网上团课学习.zip", class)
		c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
		c.Writer.Header().Add("Content-Type", "application/octet-stream")
		downfilePath := fmt.Sprintf("export/%s/z.zip", class)
		c.File(downfilePath)

	} else {
		c.HTML(http.StatusOK, "hint.html", gin.H{
			"msg": "请求错误,请稍后再试",
		})
	}

}
